package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNoSelectedException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    SetMealMapper setMealMapper;
    @Autowired
    SetMealDishMapper setMealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 菜品的分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Transactional
    @Override
    public PageResult selectByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> dishList = dishMapper.selectByPage(dishPageQueryDTO.getName(), dishPageQueryDTO.getCategoryId(), dishPageQueryDTO.getStatus());
        dishList.stream().map((item)->{
            Long categoryId1 = item.getCategoryId();
            String categoryName = categoryMapper.getNameById(categoryId1);
            item.setCategoryName(categoryName);
            return item;
        }).collect(Collectors.toList());

        Page<DishVO> dishPage = (Page<DishVO>) dishList;

        PageResult pageResult = new PageResult(dishPage.getTotal(), dishPage.getResult());
        return pageResult;
    }

    @Transactional
    @Override
    public DishVO selectById(Long id) {
        //查询菜品对应的口味信息
        List<DishFlavor> flavorList = dishMapper.selectFlavorsByDishId(id);
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = DishVO.builder()
                .flavors(flavorList)
                .build();

        BeanUtils.copyProperties(dish, dishVO);

        return dishVO;
    }

    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //如果菜品被修改就删除该分类id的所有缓存
        String key = "dish::"+dishDTO.getCategoryId();
        cleanCache(key);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        Long dishId = dishDTO.getId();
        flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //修改菜品对应的口味表的数据
        List<Long> dishIds = List.of(dishId);
        dishFlavorMapper.deleteById(dishIds);
        if (flavors!=null&&flavors.size()>0){
            dishFlavorMapper.insertFlavors(flavors);
        }


        Dish dish = new Dish();
        //复制dishDTO中的对应属性值给dish
        BeanUtils.copyProperties(dishDTO, dish);

        //修改dish表的数据
        dishMapper.update(dish);
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        if (ids==null||ids.size()==0){
            //没有勾选需要批量删除的菜品
            throw new DeletionNoSelectedException(MessageConstant.NO_SELECTED_EXCEPTION);
        }
      //批量删除就删除所有分类下的菜品缓存
        cleanCache("dish::*");

        for (int  i= 0; i < ids.size(); i++) {
            Dish dish=dishMapper.getById(ids.get(i));
            if (dish.getStatus()== StatusConstant.ENABLE){
                //当前菜品处于起售状态，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否与套餐关联，如果关联不能删除，如果没有关联直接删除
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByIds(ids);
        if (setMealIds!=null && setMealIds.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品数据；删除菜品口味表中的数据
        dishMapper.deleteByIds(ids);
         dishFlavorMapper.deleteById(ids);

    }

    @Transactional
    @Override
    public void changeStatus(Integer status, Integer id) {
        //修改菜品状态就删除缓存中所有分类下的菜品缓存
        cleanCache("dish::*");

        Long dishId = Long.valueOf(id.toString());

        Dish dish = Dish.builder()
                .status(status)
                .id(dishId)
                .build();
        dishMapper.changeStatus(dish);
    }

    @Transactional
    @Override
    public void insert(DishDTO dishDTO) {
        //如果有新菜品插入就删除该分类id的下的菜品缓存
        String key = "dish::"+dishDTO.getCategoryId();
        cleanCache(key);

        List<DishFlavor> flavors = dishDTO.getFlavors();

        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);
        //获取dish插入数据后自动生成id
        Long id = dish.getId();

        flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //在口味表中也插入菜品对应的口味数据
        dishFlavorMapper.insertFlavors(flavors);

    }

    @Override
    public List<Dish> list(Long categoryId,String name) {

        List<Dish> dishList=dishMapper.selectByCategoryId(categoryId,name);
        return dishList;
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectByCategoryId(dish.getCategoryId(),dish.getName());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishMapper.selectFlavorsByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
